
const Node=require("./Node")
class LinkList{
    constructor() {
        this.head=null //头节点
        this.size=0
    }
    print(){
        let current=this.head
        let result=[]
        while(current){
            result.push(current.data)
            current=current.next
        }
        console.log(result.join(" ——> ")+" ——> null");
    }
    //1.向链表后面添加一个数据
    push(data){
        let newNode=new Node(data)
        this.size++
        if(!this.head){
            this.head=newNode
        }
        else{
            let current=this.head
            while(current.next){
                current=current.next
            }
            current.next= newNode
        }
    }
    //2.向指定位置添加一个元素
    addValueAt(data,index){
         if(index<0 || index>this.size){
                throw new Error("索引值无效！")
         }
        else{
            let newNode=new Node(data)
            let current=this.head
            let counter=0
             this.size++
            if(index===0){
                newNode.next=current
                this.head=newNode
            }
            else{
                while(current.next ){
                   if(counter===index-1){
                       newNode.next=current.next
                       current.next=newNode
                       break
                   }
                   current=current.next
                    counter++
                }
            }
        }
    }

    //3.删除指定数据
    removeData(data){
        let current = this.head;
        let previous = null;
        while (current !== null) {
            if (current.data === data) {
                if (previous === null) {
                    this.head = current.next;
                    current = this.head; // 注意更新 current
                } else {
                    previous.next = current.next;
                    current = current.next; // 注意更新 current
                }
                this.size--;
                // 不更新 previous，因为 current 已经变了
            } else {
                previous = current;
                current = current.next;
            }
        }
    }


}
module.exports= LinkList
